//
//  HomePageViewController.m
//  sellHouse
//
//  Created by 李 佳伟 on 2018/11/20.
//  Copyright © 2018年 李 佳伟. All rights reserved.
//

#import "HomePageViewController.h"
#import "JTCSM.h"
#import "home_QuestionTableViewCell.h"
#import "Home_headerTableViewCell.h"
#import "Home_MiddleTableViewCell.h"
#import "home_bottomTableViewCell.h"
#import "LoadData.h"
#import "InvestorsModel.h"
#import "Reachability.h"

static CGFloat tagImagesize = 20;
static CGFloat header_sectionHeight = 40;
@interface HomePageViewController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate,UITextFieldDelegate,UIAlertViewDelegate>
{
   
    NSDictionary *_provinceDic;
    NSArray *_provinceArray;
    NSMutableArray *_isExpandArray;//记录section是否展开
    NSString *person_number;
    NSString *customPhone_number;
    BOOL isLoad ;
    BOOL Istouch;
    
}
@property (nonatomic,strong)  UITableView *provinceTableView;
@property(nonatomic,strong) NSMutableArray *invertorsArray;
@property(nonatomic,strong) NSMutableArray *hezuoArray ;
@property(nonatomic,strong) NSString *isHavePhone ;
@property (nonatomic,strong) ShowImageView*headerImagev;
@end

@implementation HomePageViewController

- (void)getnetwork{
    isLoad = YES;
    Istouch = YES;
    Reachability* reach = [Reachability reachabilityWithHostname:@"www.apple.com"];
    NSLog(@"-- current status: %@", reach.currentReachabilityString);
    
    // start the notifier which will cause the reachability object to retain itself!
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name:kReachabilityChangedNotification
                                               object:nil];
    
    [reach startNotifier];
    reach.unreachableBlock = ^(Reachability * reachability)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [df showAlertWithTitle:@"提示" message:@"网络不可用,请查看设置--是否允许使用网络" btn1:@"知道了" btn2:nil btn3:nil delegate:nil tag:0];
        });
    };

}
- (void)reachabilityChanged:(NSNotification *)notifi{
    
    NetworkStatus NetStatus = [notifi.object currentReachabilityStatus];
    //由于首次安装 app，会弹出请求网络权限“是否允许使用数据” 允许之前没网  允许之后才有网 有网后 通知去下载首页的数据
    if (NetStatus != NotReachable) {
        if (isLoad) {
            isLoad = NO;
            [self getRequest];
        }
        
    }else{
        
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [df isRemoveTarbar:NO];
    if (!isLoad) {
         [self getRequest];
    }
    
//    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:NO];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
//    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:NO];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.barStyle = UIStatusBarStyleLightContent;
    UIView *stateView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWidth, Height_StatusBar)];
    stateView.backgroundColor =[UIColor whiteColor];
//    [df colorWithHexString:@"0fa6e8" alpha:1];
    [self.view addSubview:stateView];
    
    [self getnetwork];
    person_number=@"";
    customPhone_number=@"";
    _isHavePhone = @"";
    [self getKefuDianhuan];
    _isExpandArray = [[NSMutableArray alloc]init];
    self.view.backgroundColor = [UIColor whiteColor];
    _invertorsArray = [NSMutableArray array];
    _hezuoArray = [NSMutableArray array];
    [self getProvinceDataFromList];
    [self initProvinceTableView];
    [JTCSMSingle shareSingle].navigationC = self.navigationController;
    [JTCSMSingle shareSingle].thevc = self;
    
}


- (void)getProvinceDataFromList{
    NSString *dataList = [[NSBundle mainBundle]pathForResource:@"QuestionList" ofType:@"plist"];
    _provinceDic = [[NSDictionary alloc]initWithContentsOfFile:dataList];
    _provinceArray = [_provinceDic allKeys];
    NSArray *result = [_provinceArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2]; //升序
    }];
    NSLog(@"result=%@",result);
    _provinceArray = result;
    for (NSInteger i = 0; i < _provinceArray.count; i++) {
        [_isExpandArray addObject:@"0"];//0:没展开 1:展开
    }
}

- (void)initProvinceTableView{
    _provinceTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, Height_StatusBar, KSCREENWidth, KSCREENHeight-Height_TabBar-Height_StatusBar) style:UITableViewStylePlain];
    _provinceTableView.delegate = self;
    _provinceTableView.dataSource = self;
    _provinceTableView.bounces = NO;
    _provinceTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    _provinceTableView.backgroundColor = [UIColor whiteColor];
    _provinceTableView.estimatedRowHeight = 0;
    _provinceTableView.estimatedSectionHeaderHeight = 0;
    _provinceTableView.estimatedSectionFooterHeight = 0;
    [self.view addSubview:_provinceTableView];
}

#pragma -- mark tableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _provinceArray.count+2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section ==0) {
        return 3;
    }else if(section==_provinceArray.count+1){
        
        return 1;
    }else{
        if ([_isExpandArray[section-1]isEqualToString:@"1"]) {
            NSString *keyProvince = _provinceArray[section-1];
            NSArray *cityArray = [_provinceDic objectForKey:keyProvince];
            return  cityArray.count;
        }else{
            return 0;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 0;
    }else if(section==_provinceArray.count+1){
        
        return 0;
    }else{
        return header_sectionHeight;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==0) {
        if (indexPath.row ==0) {
            return [UITableViewCell whc_CellHeightForIndexPath:indexPath tableView:tableView];
        }else if(indexPath.row ==1){
            return [Home_headerTableViewCell whc_CellHeightForIndexPath:indexPath tableView:tableView];
        }else{
            return [Home_MiddleTableViewCell whc_CellHeightForIndexPath:indexPath tableView:tableView];
        }
    }else if(indexPath.section ==_provinceArray.count+1){
        
        return [home_bottomTableViewCell whc_CellHeightForIndexPath:indexPath tableView:tableView];
    }else{
        return [home_QuestionTableViewCell whc_CellHeightForIndexPath:indexPath tableView:tableView];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section ==0 || section == _provinceArray.count+1) {
        return nil;
    }else{
        UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWidth, header_sectionHeight)];
        headerView.backgroundColor = [UIColor whiteColor];
        [df lineViewWithHeightofTop:headerView.frame.size.height superView:headerView lineHeight:1 space:Kspace];
        UILabel *provinceLabel = [[UILabel alloc]initWithFrame:CGRectMake(Kspace, 0, KSCREENWidth-3*Kspace-tagImagesize, header_sectionHeight)];
        provinceLabel.textColor = RGBACOLOR(51, 51, 51, 1);
        provinceLabel.text = _provinceArray[section-1];
        provinceLabel.font = [UIFont systemFontOfSize:15];
        [headerView addSubview:provinceLabel];
        [df fuwenbenLabel:provinceLabel FontNumber:[UIFont systemFontOfSize:15] AndRange:NSMakeRange(0, 2) AndColor:RGBACOLOR(15, 166, 231, 1)];
        UIImageView *selectImageView = [[UIImageView alloc]initWithFrame:CGRectMake(KSCREENWidth-Kspace-tagImagesize, (header_sectionHeight-tagImagesize)/2, tagImagesize, tagImagesize)];
        [headerView addSubview:selectImageView];
        if ([_isExpandArray[section-1] isEqualToString:@"0"]) {
            //未展开
            selectImageView.image = [UIImage imageNamed:@"xiangxia2.jpg"];
        }else{
            //展开
            selectImageView.image = [UIImage imageNamed:@"xiangshang.jpg"];
        }
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
        tap.delegate = self;
        [headerView addGestureRecognizer:tap];
        headerView.tag = section;
        return headerView;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section ==0){
        NSString *iditifier =[NSString stringWithFormat:@"%ld-%ld",(long)indexPath.section,(long)indexPath.row];
        if (indexPath.row ==0) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:iditifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:iditifier];
                self.headerImagev = [[ShowImageView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWidth, KSCREENWidth*238/450)];
                [cell.contentView addSubview:_headerImagev];
                NSArray *imagenameArray = @[@"homeimage1.jpg",@"homeimage2.jpg"];
                [self.headerImagev home_viewDidLoadWithImageArray:imagenameArray];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else if (indexPath.row == 1) {
            Home_headerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:iditifier];
            if (cell ==nil) {
                cell = [[Home_headerTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:iditifier];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.textfield.delegate = self;
            [cell.textfield addTarget:self action:@selector(textField1TextChange:) forControlEvents:UIControlEventEditingChanged];
            cell.textfield.returnKeyType = UIReturnKeyDone;
            if (KUSERDEFAULTGET(KuserInfo) !=nil) {
                if (KHkTellString !=nil && ![KHkTellString isEqualToString:@""]) {
                    cell.textfield.enabled = NO;
                    cell.textfield.text = KTurnToString(KHkTellString);
                    _isHavePhone = KTurnToString(KHkTellString);
                }else{
                    cell.textfield.enabled = YES;
                    _isHavePhone = cell.textfield.text;
                }
            }else{
                _isHavePhone=@"";
                cell.textfield.text = @"";
            }
            
            [cell setValueWithPersonNumber:person_number];
            [df addTapGestureRecognizerWithTarget:self action:@selector(gujia) andaddView:cell.house_priceLabel];
            [df addTapGestureRecognizerWithTarget:self action:@selector(sellhouse) andaddView:cell.sellHouseLabel];
            [df addTapGestureRecognizerWithTarget:self action:@selector(callphone) andaddView:cell.phone_sellLabel];
            return cell;
        }else {
            Home_MiddleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:iditifier];
            if (cell ==nil) {
                cell = [[Home_MiddleTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:iditifier];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        
    }else if(indexPath.section ==_provinceArray.count+1){
        
        NSString *iditifier =[NSString stringWithFormat:@"%ld-%ld",(long)indexPath.section,(long)indexPath.row];
        home_bottomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:iditifier];
        if (cell ==nil) {
            cell = [[home_bottomTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:iditifier];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setValueWithInvestoursModel:_invertorsArray hezuoModle:_hezuoArray];
        return cell;
    }else{
        NSString *iditifier = @"CityTableViewCell";
        home_QuestionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:iditifier];
        if (cell == nil) {
            cell = [[home_QuestionTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:iditifier];
        }
        NSString *keyOfProvince = _provinceArray[indexPath.section-1];
        NSArray *cityArray = [_provinceDic objectForKey:keyOfProvince];
        [cell setContentLabel_textWithText:cityArray[indexPath.row]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
    }
}

- (void)tapAction:(UITapGestureRecognizer *)tap{
    if ([_isExpandArray[tap.view.tag-1] isEqualToString:@"0"]) {
        //关闭 => 展开
        [_isExpandArray replaceObjectAtIndex:tap.view.tag-1 withObject:@"1"];
    }else{
        //展开 => 关闭
        [_isExpandArray replaceObjectAtIndex:tap.view.tag-1 withObject:@"0"];
    }
    NSIndexSet *set = [NSIndexSet indexSetWithIndex:tap.view.tag];
    [_provinceTableView reloadSections:set withRowAnimation:UITableViewRowAnimationFade];
    
}
#pragma mark 极速卖房
- (void)sellhouse{
   
    [self.view endEditing:YES];
    if (Istouch) {
        Istouch = NO;
        if (![_isHavePhone isEqualToString:@""] && _isHavePhone != nil) {
            if ([df isValidMobile:_isHavePhone]) {
                [self insertMsaleTellRequestWithPhone:_isHavePhone];
            }else{
                Istouch = YES;
                [df showAlertWithTitle:@"提示" message:@"手机号不正确" btn1:@"知道了" btn2:nil btn3:nil delegate:nil tag:0];
            }
        }else{
            Istouch = YES;
            [df showAlertWithTitle:@"提示" message:@"请输入手机号" btn1:@"知道了" btn2:nil btn3:nil delegate:nil tag:0];
        }
    }
    
    
   
}

#pragma mark 房屋估计
- (void)gujia{
    WebViewController *vc = [[WebViewController alloc]init];
    vc.urlStr = KWEBURLHEADER(@"Assessment.html");
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma marke 网络请求
- (void)getRequest{
 
    __block HomePageViewController *myself =  self;
    [self.invertorsArray removeAllObjects];
    [self.hezuoArray removeAllObjects];
    
    [[LoadData object] loadDataPostAsynchronousWithURL:@"sysconf/getInvestors" withDict:@{} superView:nil Block:^(id  _Nullable responseObject) {
        if (responseObject ==nil) {
            //            [df showAlertWithTitle:@"提示" message:@"请求失败" btn1:@"知道了" btn2:nil btn3:nil delegate:nil tag:0];
            return ;
        }
        NSArray *array = [responseObject objectForKey:@"data"];
        if (array.count>0) {
            for (NSDictionary *dict in array) {
                InvestorsModel *model = [InvestorsModel whc_ModelWithJson:dict];
                if (model != nil) {
                     [myself.invertorsArray addObject:model];
                }
               
            }
        }
        
        [[LoadData object] loadDataPostAsynchronousWithURL:@"sysconf/getPartners" withDict:@{} superView:nil Block:^(id  _Nullable responseObject) {
            if (responseObject ==nil) {
                //            [df showAlertWithTitle:@"提示" message:@"请求失败" btn1:@"知道了" btn2:nil btn3:nil delegate:nil tag:0];
                return ;
            }
                NSArray *array = [responseObject objectForKey:@"data"];
                for (NSString *url in array) {
                    [myself.hezuoArray addObject:url];
                }
            [self getPersonNumberRequest];

        }];
    }];
    
}
#pragma mark 委托人数量请求
- (void)getPersonNumberRequest{
    __block HomePageViewController *myself =  self;
    [[LoadData object] loadDataPostAsynchronousWithURL:@"index/getSaleHouseCount" withDict:@{} superView:nil Block:^(id  _Nullable responseObject) {
        
        NSLog(@"-------%@",KResponseData);
        myself->person_number = KResponseData;
        [myself.provinceTableView reloadData];
        Istouch = YES;
    }];
}

#pragma mark 保存手机号
- (void)insertMsaleTellRequestWithPhone:(NSString *)phone{
    if (KUSERDEFAULTGET(KuserInfo) !=nil) {
        [self gotoWebview];
    }else{
        __block HomePageViewController *myself =  self;
        _isHavePhone= @"";
        [[LoadData object] loadDataPostAsynchronousWithURL:@"index/insertMsaleTell" withDict:@{@"tel":phone} superView:nil Block:^(id  _Nullable responseObject) {
            myself.isHavePhone = phone;
            [myself gotoWebview];
            
        }];
    }
   
    
}
#pragma mark 跳转web页
-(void)gotoWebview{
    WebViewController *vc = [[WebViewController alloc]init];
    vc.urlStr = KWEBURLHEADER(@"QuickSeller.html");
    vc.phone = _isHavePhone;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)textField1TextChange:(UITextField *)textfield{
    _isHavePhone= textfield.text;
}
#pragma mark textfieldDelegate
//实现UITextField代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];//取消第一响应者
    NSLog(@"%@",textField.text);
    
    return YES;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"%d",alertView.tag);
    
    if (alertView.tag ==10000+KAlertVTag) {
        if (buttonIndex==0) {
            
        }
    }
}

#pragma mark 拨打电话
- (void)callphone{
    NSMutableString* str=[[NSMutableString alloc] initWithFormat:@"tel:%@",customPhone_number];
    
    UIWebView * callWebview = [[UIWebView alloc] init];
    
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    
    [self.view addSubview:callWebview];
}

#pragma mark 客服电话请求
- (void)getKefuDianhuan{
    [[LoadData object] loadDataPostAsynchronousWithURL:@"sysconf/getTell" withDict:@{} superView:nil Block:^(id  _Nullable responseObject) {
        self->customPhone_number = KTurnToString(KResponseData);
    }];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
